package com.example.certificate.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.example.certificate.execption.BusinessException;
import com.example.certificate.utils.CodeEntity;
import com.example.certificate.utils.RedisTemplateUtil;
import com.example.certificate.utils.ResultConstant;
import com.example.certificate.utils.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Slf4j
@Component
@Service
public class CodeService {


    @Autowired
    private RedisTemplateUtil redisUtils;

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    static final String accessKeyId = "LTAI4G5RT31y789b5kyRek68";
    static final String accessKeySecret = "T9kySxc16IAQTGNtrl202cDX0b3YzR";

    public SendSmsResponse sendSms(String telphone, String templateId,Integer type) throws ClientException, BusinessException {
        //正则验证手机号
        String ph = "^1[3|5|7|8]{1}[0-9]{9}$";
        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);

        if (telphone.matches(ph)) {
            //待发送的手机号
            request.setPhoneNumbers(telphone);
        }
        //短信签名
        request.setSignName("醒心Sunset");
        //短信模板ID
        request.setTemplateCode(templateId);
        //验证码
        CodeEntity code = new CodeEntity();
        code.setCode();
        String codetemp = code.getCode() + "";

        System.out.println("code:" + codetemp);
        /*
         * 可选:模板中的变量替换JSON串,
         * 如模板内容为"亲爱的${name},您的验证码为${code}"时,
         * 此处的值为{"name":"Tom","code":"1454"}
         *   \  反斜杠为转义字符，使得输出双引号
         */
        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"" + codetemp + "\"}");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("1454");

        //TODO 为了测试 暂时屏蔽短信发送 默认验证码1234
        SendSmsResponse response =  new SendSmsResponse();
        response.setCode("OK");
        response.setMessage(codetemp);
        if (response.getCode() != null && response.getCode().equals("OK")) {
            saveToRedis(telphone+"_"+type, codetemp);
        } else {
            throw new BusinessException(ResultConstant.SEND_CODE_LOSE.resultCode,ResultConstant.SEND_CODE_LOSE.message);
        }
        return response;
    }


    public ResultEntity checkMobile(String mobile, String code, Integer type) throws BusinessException {
        String tmpCodeStr = this.getCode(mobile+"_"+type);
        if (!StringUtils.isEmpty(tmpCodeStr)) {
            JSONObject tmpCode = JSONObject.parseObject(tmpCodeStr);
            if (tmpCode.get("code") != null && tmpCode.get("code").equals(code)) {
            } else {
                throw new BusinessException(ResultConstant.SEND_CODE_MISTAKE.resultCode, "验证码不正确");
            }
        } else {
            throw new BusinessException(ResultConstant.SEND_CODE_MISTAKE.resultCode, "验证码不正确");
        }
        return new ResultEntity();
    }


    private void saveToRedis(String key, String value) {
        String codeStr = getCode(key);
        Integer counts = 1;
        if (!StringUtils.isEmpty(codeStr)) {
            JSONObject tmpCode = JSONObject.parseObject(codeStr);
            counts = Integer.valueOf(tmpCode.get("counts").toString());
            redisUtils.delete(key);
            counts = counts + 1;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", value);
        jsonObject.put("counts", counts);
        redisUtils.setValExpire(key,jsonObject.toJSONString());
    }

    /**
     * 根据key 到Redis中查询出验证码
     * @return
     */
    public String getCode(String Key) {
        return (String) redisUtils.getVal(Key);
    }

}
